<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请编号" prop="applicationNo">
        <el-input
          v-model="queryParams.applicationNo"
          placeholder="请输入申请编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入申请人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入付款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款人" prop="payee">
        <el-input
          v-model="queryParams.payee"
          placeholder="请输入收款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
                        v-model="queryParams.applicationTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批人ID" prop="approvalUserId">
        <el-input
          v-model="queryParams.approvalUserId"
          placeholder="请输入审批人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择审批状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.fm_ra_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fm:pa:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fm:pa:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="project.projectNo" />
      <el-table-column label="项目名称" align="center" prop="project.projectName" />
      <el-table-column label="申请编号" align="center" prop="applicationNo" />
      <el-table-column label="付款金额" align="center" prop="amount" />
      <el-table-column label="请款类别" align="center" prop="type" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fm_pa_rc" :value="scope.row.type" :dictName="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="付款原因" align="center" prop="reason" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fm_ra_status" :value="scope.row.status" :dictName="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="审批备注" align="center" prop="approvalRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fm:pa:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fm:pa:del']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!--添加/编辑/查看表单-->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="申请编号" prop="applicationNo">
              <el-input v-model="form.applicationNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 申请人（当前登录用户） -->
            <el-form-item label="申请人" prop="userName">
              <el-input v-model="form.userName" placeholder="当前登录用户" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="form.projectNo" placeholder="根据项目自动匹配" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 1. 修正项目选择器的v-model绑定 -->
            <el-form-item label="项目名称" prop="projectId">
              <el-select
                v-model="form.projectId"
                placeholder="请选择项目"
                @change="handleProjectChange"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 申请时间 -->
            <el-form-item label="申请时间" prop="applicationTime">
              <el-date-picker
                clearable
                v-model="form.applicationTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择申请时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 报销金额 -->
            <el-form-item label="报销金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入报销金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请款类别" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择请款类别">
                <el-option
                  v-for="dict in dict.type.fm_pa_rc"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 请款内容 -->
            <el-form-item label="请款内容" prop="reason">
              <el-input v-model="form.reason" type="textarea" placeholder="请输入请款内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="8">
            <!-- 收款方式 -->
            <el-form-item label="收款方式" prop="paymentMethod">
              <el-select
                v-model="form.paymentMethod"
                placeholder="请选择收款方式">
                <el-option
                  v-for="dict in dict.type.fm_ra_pm"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 收款人姓名 -->
            <el-form-item label="收款人姓名" prop="payee">
              <el-input v-model="form.payee" placeholder="请输入收款人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 收款银行 -->
            <el-form-item label="收款银行" prop="receiveBank">
              <el-select
                v-model="form.receiveBank"
                placeholder="请选择收款银行">
                <el-option
                  v-for="dict in dict.type.sys_re_bank"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 收款账号 -->
            <el-form-item label="收款账号" prop="receiveAccount">
              <el-input v-model="form.receiveAccount" placeholder="请输入收款账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <el-col :span="8">
          <!-- 申请时间 -->
          <el-form-item label="审批时间" prop="approvalTime">
            <el-date-picker
              clearable
              v-model="form.approvalTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择审批时间"
            />
          </el-form-item>
        </el-col>
          <el-col :span="8">
        <!-- 备注 -->
        <el-form-item label="审批备注" prop="approvalRemark" v-if="isApprovalView">
          <el-input v-model="form.approvalRemark" type="textarea" plceholder="请输入审批备注信息" disabled/>
        </el-form-item>
          </el-col>
        </el-row>
        <el-divider/>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12" align="">
            <el-button v-if="isSub" type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplication, getApplication, delApplication, addApplication, updateApplication } from "@/api/system/fm/pa"
import {parseTime} from "../../../utils/ruoyi";
import dict from "@/utils/dict";
import {getAllProject} from "@/api/pm/projects";

export default {
  name: "Application",
  dicts:["fm_pa_rc","fm_ra_pm","fm_ra_status","sys_re_bank"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款申请表格数据
      applicationList: [],
      isSub:false,
      // 项目列表（后端返回的所有项目数据）
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 有关审批内容显示时机
      isApprovalView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationNo: null,
        userId: null,
        projectId: null,
        amount: null,
        payee: null,
        receiveBank: null,
        receiveAccount: null,
        paymentMethod: null,
        type: null,
        reason: null,
        applicationTime: null,
        status: null,
        approvalUserId: null,
        approvalTime: null,
        approvalRemark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // 修正：移除冗余的userId和status校验，保持必要校验
        projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
        applicationTime: [{ required: true, message: "请选择申请时间", trigger: "change" }],
        amount: [
          { required: true, message: "请输入报销金额", trigger: "blur" },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效金额（最多两位小数）", trigger: "blur" }
        ],
        reason: [{ required: true, message: "请输入请款内容", trigger: "blur" }],
        paymentMethod: [{ required: true, message: "请选择收款方式", trigger: "change" }],
        payName: [{ required: true, message: "请输入收款人姓名", trigger: "blur" }],
        // 修正：根据收款方式动态校验银行和账号
        receiveBank: [
          { required: () => this.form.paymentMethod === '2', message: "请输入收款银行", trigger: "blur" }
        ],
        receiveAccount: [
          { required: () => this.form.paymentMethod === '2', message: "请输入收款账号", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    // 初始化时获取项目列表
    this.loadProjectOptions();
  },
  methods: {
    dict,
    parseTime,
    /** 查询付款申请列表 */
    getList() {
      this.loading = true
      listApplication(this.queryParams).then(response => {
        this.applicationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicationNo: null,
        userId: null,
        projectId: null,
        amount: null,
        payee: null,
        receiveBank: null,
        receiveAccount: null,
        paymentMethod: null,
        type: null,
        reason: null,
        applicationTime: null,
        status: null,
        approvalUserId: null,
        approvalTime: null,
        approvalRemark: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isApprovalView = false
      this.open = true
      this.isSub = true
      this.title = "添加付款申请"
      // 新增：默认申请时间为今天
      this.form.applicationTime = parseTime(new Date(), '{y}-{m}-{d}')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getApplication(id).then(response => {
        this.form = response.data
        // 新增：从user对象中提取userName
        this.form.userName = response.data.user?.userName || ''
        this.open = true
        this.title = "修改付款申请"
        this.isApprovalView = false
        this.isSub = true
      })
    },
    // 修改 handleView 方法中的项目信息回显逻辑
    handleView(row) {
      this.reset()
      this.open = true
      this.isApprovalView = true
      this.isSub = false
      this.title = "查看报销申请"
      // 深拷贝防止修改原数据
      this.form = {...row}
      // 处理项目信息回显 - 关键修复：使用row.projectId而非row.project.id
      this.form.projectId = row.projectId;  // 直接使用报销表中的projectId
      // 从项目列表中找到对应的项目信息
      const project = this.projectList.find(p => p.id === row.projectId);
      if (project) {
        this.form.projectNo = project.projectNo;
      }
      this.form.paymentMethod = this.form.paymentMethod?.toString();  // 转换为字符串
      // 新增：从user对象中提取userName
      this.form.userName = row.user?.userName || ''
    },
    loadProjectOptions() {
      getAllProject().then(response => {
        // 正确写法：从response中提取data字段的数组
        this.projectList = response.data || [];  // 关键修复：添加 .data
      }).catch(err => {
        console.error('加载项目列表失败', err);
      })
    },
    // 2. 处理项目选择变化（核心联动逻辑）
    handleProjectChange(val) {
      if (!val) {
        this.form.projectNo = "";
        return;
      }
      // 从项目列表中找到选中的项目
      const selectedProject = this.projectList.find(item => item.id === val);
      if (selectedProject) {
        // 自动填充项目编号
        this.form.projectNo = selectedProject.projectNo || "";
      } else {
        this.form.projectNo = "";
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApplication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除付款申请编号为"' + ids + '"的数据项？').then(function() {
        return delApplication(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fm/pa/export', {
        ...this.queryParams
      }, `application_${new Date().getTime()}.xlsx`)
    }
  },
  // 3. 监听项目ID变化，确保联动生效
  watch: {
    'form.projectId'(val) {
      this.handleProjectChange(val);
    }
  }
}
</script>
